import { Component, OnInit } from '@angular/core';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {Router} from '@angular/router';
import {component_appid, redirect_uri} from '../../../../config/api';
import {AppletSettingService} from '../applet-setting.service';
import {NzMessageService} from "ng-zorro-antd";
import { environment } from '../../../../environments/environment';
console.log(environment);
@Component({
  selector: 'app-authorization',
  templateUrl: './authorization.component.html',
  styleUrls: ['./authorization.component.scss'],
  providers: [AppletSettingService]
})
export class AuthorizationComponent implements OnInit {
  pre_auth_code = 'preauthcode@@@4XF4VfYo19rKLdA86BBgC2sL97T2BT8ri9E14cGI4LsfGEtIQaHISaJ6MawC5dAU';
  authorization_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=';
  authorization_info;
  appletInfo;
  wxauthorization = ['帐号管理权限', '开发管理与数据分析权限', '开放平台帐号管理权限', '小程序基本信息设置权限', '小程序认证权限'];
  wxauthorizationType = [];
  type;
  _isSpinning = false;
  wx_category = [];
  wx_second_class = [];
  webviewdomain=environment.webviewdomain;
  needAuth=false;
  constructor(private router: Router,
              private localStorageService: LocalStorageService,
              private appletSettingService: AppletSettingService,
              private _message: NzMessageService,
              ) { }

  ngOnInit() {
    this.getAuthCallBack();
  }

  gotoWechatGetAuthorization() {
    // 获取微信预授权码
    this.appletSettingService.gotoWechatGetAuthorization().subscribe(
      res => {
        if (res.code === 2000) {
          this.pre_auth_code = res.data.pre_auth_code;
          const gotourl = this.authorization_url + component_appid + '&pre_auth_code=' + this.pre_auth_code + '&redirect_uri=' + redirect_uri;
          window.location.href = gotourl;
          // window.open(gotourl);
        } else {
          alert(res.message);
        }
      }
    );
  }

  //业务域名授权
  setAuth(){
    this._isSpinning=true;
    let applet_uuid=this.localStorageService.getNowApplet().applet_uuid;
    this.appletSettingService.setWebviewdomain(applet_uuid).subscribe(res=>{
      if (res.code==2000) {
        this.needAuth=false;
      }else{
        alert(res.message);
      }
      this._isSpinning=false;
    });
  }

  checkDomain(domains){
    let webviewdomain=this.webviewdomain;
    let result=true;
    webviewdomain.forEach(item=>{
      if (domains.indexOf(item)<0) {
        result=false;
      }
    })
    return result;
  }

  // 获取url上的参数确定授权信息
  getAuthCallBack() {
    this._isSpinning = true;
    const addressUrl = location.search.slice(1);
    const searchParams = new URLSearchParams(addressUrl);

    let auth_code = searchParams.get('auth_code');
    if (!auth_code) {
      auth_code = '';
    }
    this.appletSettingService.getAuthorizationInfo({
      authorization_code: auth_code
    }).subscribe(res => {
      this._isSpinning = false;
      if (res.code === 2000) {
        if (auth_code) {
          this._message.create('success', '授权成功');
        }
        if (res.data.appletInfo.applet_auth) {
          this.wxauthorization.forEach((val, i) => {
            this.wxauthorizationType[i] = res.data.appletInfo.applet_auth.indexOf(val) > -1;
          });
          res.data.appletInfo.wx_category.forEach((val) => {
            if (this.wx_second_class.indexOf(val.second_class) === -1) {
              this.wx_second_class.push(val.second_class);
              this.wx_category.push(val);
            }
          });
          if (res.data.appletInfo.applet_auth.length === 5) {
            this.type = 0;
          } else if (res.data.appletInfo.applet_auth.length === 0) {
            this.type = 2;
          } else {
            this.type = 1;
          }
          this.appletInfo = res.data.appletInfo;
          if (res.data.ssg) {
            let ssg=JSON.parse(res.data.ssg);
            console.log(ssg.webviewdomain);
            if (ssg.webviewdomain.length==0 || !this.checkDomain(ssg.webviewdomain) ) {
              this.needAuth=true;
            }
          }

        } else {
          this.type = 2;
        }
      } else if (res.code === 4000 && res.message === '小程序未绑定或未授权，请先绑定或授权') {
        this.type = 2;
      } else {
        this._message.create('error', res.code + ' ' + res.message, {nzDuration: 3000});
        this.type = 2;
      }
    });
  }
}
